package com.sinosoft.dsp.security.services;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.servlet.http.HttpSession;

import com.sinosoft.dsp.persistence.hibernate.bo.SystemSecurityBo;
import com.sinosoft.dsp.platform.utils.FacesContextUtils;
import com.sinosoft.dsp.platform.utils.MessageBundles;
import com.sinosoft.dsp.platform.utils.SinoManagedBean;
import com.sinosoft.dsp.security.utils.AuthenticationStatus;
import com.sinosoft.dsp.system.core.log.Log;
import com.sinosoft.dsp.system.entity.ISecurityUser;
import com.sinosoft.dsp.system.utils.Const;
import com.sinosoft.dsp.system.utils.HashUtils;

@ManagedBean(name = "sinoAuthenticator")
@SessionScoped
public class SinoAuthenticator implements Serializable {

	private static final long serialVersionUID = 5670546258198645317L;

	public static final String SECURITY_USER_CLASS_NAME = "com.sinosoft.dsp.system.entity.user.SinoUserInfo";

	private static final Log log = Log
			.getLog(SinoAuthenticator.class.getName());

	@ManagedProperty(value = "#{systemSecurityBo}")
	private SystemSecurityBo securityBo;

	@ManagedProperty(value = "#{messageBundles}")
	private MessageBundles messageBundles;

	private String username;

	private String password;

	private AuthenticationStatus status = AuthenticationStatus.FAILURE;

	/**
	 * 当前登录用户
	 */
	private ISecurityUser currentUser;

	/**
	 * 功能导航ID的Map
	 */
	private Map<String, Object> naviIdMap = new HashMap<String, Object>();

	/**
	 * 所属组件机构ID类别
	 */
	private List<String> orgIdList = new ArrayList<String>();

	/**
	 * 用户拥有的权限ID的Map
	 */
	private Map<String, Object> roleIdMap = new HashMap<String, Object>();

	public void login() {
		log.debug("用户登录： " + username);
		if (Const.isEmpty(username)) {
			status = AuthenticationStatus.FAILURE;
			FacesContextUtils.addGlobalErrorFacesMessage(messageBundles
					.getValue("account.login.validUsername"));
		} else {
//			ISecurityUser user = securityBo.findUserByName(username);
//
//			// 用户状态为不可用
//			if (user != null) {
//				if (user.getPassword().trim().equals(
//						HashUtils.hashPassword(password.trim()))) {
//					status = AuthenticationStatus.SUCCESS;
//					password = null;
//					currentUser = user;
//
//					reloadUserResource();
//
//					FacesContextUtils.addGlobalFacesMessage(
//							FacesMessage.SEVERITY_INFO, messageBundles
//									.getValue("account.login.loginSuccessful"));
//					return;
//
//				}
//
//			}
//
//			status = AuthenticationStatus.FAILURE;
//			password = null;
//			FacesContextUtils.addGlobalErrorFacesMessage(messageBundles
//					.getValue("account.login.validPassword"));
			status = AuthenticationStatus.SUCCESS;
			FacesContextUtils.addGlobalFacesMessage(
					FacesMessage.SEVERITY_INFO, messageBundles
							.getValue("account.login.loginSuccessful"));
			return;
		}
	}

	/**
	 * 登出系统
	 */
	public void logout() {
		log.debug("用户登出：" + username);
		password = null;
		currentUser = null;
		status = AuthenticationStatus.FAILURE;
		HttpSession session = FacesContextUtils.getSession(false);
		if (session != null) {
			session.invalidate();
		}

	}

	/**
	 * 加载用户资源
	 * 
	 * @return
	 */
	public boolean reloadUserResource() {
		try {
			if (currentUser != null
					&& !Const.isEmpty(currentUser.getUseruuid())) {
				loadUserNavi(currentUser.getUseruuid());
				loadUserOrg(currentUser.getUseruuid());
				loadUserRole(currentUser.getUseruuid());
				updateUser(currentUser.getUseruuid());
			}
			return true;
		} catch (Exception e) {
			log.error("加载用户资源出现错误！");
		}
		return false;
	}

	/**
	 * 登录验证成功之后，更新登录次数加1，记录最后一次ip
	 */
	public void updateUser(String userId) {
		try {
			// 获得用户服务
//			IUserService userService = SinoManagedBean.findBean("userService");
//			SysUser user = userService.findById(currentUser.getUseruuid()
//					.trim());
//			if (user != null) {
//				user.setLastLoginIp(FacesContextUtils.getRequest()
//						.getRemoteHost().toString());
//				userService.merge(user);
//			}
		} catch (Exception e) {
			log.error("记录最后一次ip出现异常.......");
		}
	}

	/**
	 * 加载用户角色功能导航
	 * 
	 * @param userId
	 */
	private void loadUserNavi(String userId) {
//		naviIdMap.clear();
//		List<?> naviMenu = securityBo.getUserNaviIdSet(userId);
//		for (Object naviId : naviMenu) {
//			naviIdMap.put((String) naviId, null);
//		}
	}

	/**
	 * 加载用户的组织机构列表
	 * 
	 * @param userId
	 */
	@SuppressWarnings("unchecked")
	private void loadUserOrg(String userId) {
//		orgIdList.clear();
//		orgIdList.addAll((List<String>) securityBo.getUserOrgIdSet(userId));
	}

	/**
	 * 加载用户的角色列表
	 * 
	 * @param userId
	 */
	private void loadUserRole(String userId) {
//		roleIdMap.clear();
//		List<?> roleIds = securityBo.getUserRoleIdSet(userId);
//		for (Object id : roleIds) {
//			roleIdMap.put((String) id, null);
//		}
	}

	/**
	 * 获得用户真实姓名
	 * 
	 * @return
	 */
	public String getUserFullName() {
		if (currentUser != null) {
			return Const.NVL(currentUser.getFullname(), "");
		}
		return messageBundles.getValue("account.current.anonymity");
	}

	/**
	 * 检查导航权限
	 * 
	 * @param naviId
	 * @return
	 */
	public boolean checkNavi(String naviId) {
		return naviIdMap.containsKey(naviId);
	}

	/**
	 * 检查角色
	 * 
	 * @param roleId
	 * @return
	 */
	public boolean checkRole(String roleId) {
		return roleIdMap.containsKey(roleId);
	}

	/**
	 * 检查组织机构
	 * 
	 * @param roleId
	 * @return
	 */
	public boolean checkOrg(String roleId) {
		for (String id : orgIdList) {
			if (id.equals(roleId)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获得用户组织机构ID的列表
	 * 
	 * @return
	 */
	public List<String> getOrgIdList() {
		return orgIdList;
	}

	public boolean getLoggedIn() {
		return status == AuthenticationStatus.SUCCESS;
	}

	public AuthenticationStatus getStatus() {
		return status;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public SystemSecurityBo getSecurityBo() {
		return securityBo;
	}

	public void setSecurityBo(SystemSecurityBo securityBo) {
		this.securityBo = securityBo;
	}

	public MessageBundles getMessageBundles() {
		return messageBundles;
	}

	public void setMessageBundles(MessageBundles messageBundles) {
		this.messageBundles = messageBundles;
	}

	public ISecurityUser getCurrentUser() {
		return currentUser;
	}

}
